package it.webrules.deploymanager.webapp.controller;

import it.webrules.deploymanager.webapp.auth.AuthenticatedUser;
import it.webrules.deploymanager.webapp.auth.DMPrincipal;
import it.webrules.deploymanager.webapp.auth.LoginCookieManager;
import it.webrules.deploymanager.webapp.service.cluster.TokenStore;
import it.webrules.deploymanager.webapp.service.persistence.UserStore;
import it.webrules.deploymanager.webapp.transentities.UserResponse;

import javax.inject.Inject;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.codehaus.jettison.json.JSONException;

import com.sun.jersey.spi.resource.PerRequest;

@PerRequest
@Path("services/login")
public class LoginController {

	@AuthenticatedUser
	private DMPrincipal user;

	@Inject
	private UserStore userStore;

	@Inject
	private TokenStore tokenStore;

	@Inject
	private LoginCookieManager loginCookieManager;

	@Inject
	public LoginController() {
	}

	@POST
	@Produces(MediaType.APPLICATION_JSON)
	public Response login(@FormParam("username") String username, @FormParam("password") String password) throws JSONException {

		if (user != null) {
			UserResponse userResponse = new UserResponse(user);
			return Response.ok(userResponse).build();
		}

		DMPrincipal user = userStore.authenticate(username, password);
		if (user != null) {
			String token = tokenStore.createToken(user);
			UserResponse userResponse = new UserResponse(user);
			return loginCookieManager.login(Response.ok(userResponse), token).build();
		}

		return Response.status(Status.UNAUTHORIZED).build();

	}

}